package org.lysh.controller;

import io.swagger.annotations.ApiModel;
import lombok.extern.slf4j.Slf4j;
import org.lysh.enums.HttpContentTypeEnum;
import org.lysh.enums.OssFolder;
import org.lysh.exception.BusinessException;
import org.lysh.response.BlogResponse;
import org.lysh.utils.file.MinioUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author liyishan
 * @date 2024/4/24 17:14
 * @apiNote
 */
@Slf4j
@RestController
@RequestMapping("file/")
@ApiModel("/文件管理")
public class FileController extends BaseController {
    @Autowired
    private MinioUtils minioUtils;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public BlogResponse<?> upload(@RequestPart("file") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        assert fileName != null;
        int lastIndexOf = fileName.lastIndexOf(".");
        HttpContentTypeEnum httpContentTypeEnum = HttpContentTypeEnum.parse(fileName.substring(lastIndexOf));
        String url = minioUtils.uploadFile(file, OssFolder.PROTOCOL, httpContentTypeEnum);
        return BlogResponse.Success(url);
    }


    /**
     * @param url      <a href="http://localhost:9000/mall/test/20240425/20150919022913sFUmNsFUmN.jpg">...</a>
     */
    @RequestMapping(value = "/download1", method = RequestMethod.GET)
    @ResponseBody
    public void download1(@RequestParam("url") String url,
                          @RequestParam("open") Boolean open,
                          HttpServletRequest request,
                          HttpServletResponse response) {
        int lastIndexOf = url.lastIndexOf(".");
        HttpContentTypeEnum httpContentTypeEnum = HttpContentTypeEnum.parse(url.substring(lastIndexOf));
        try {
            minioUtils.downloadFile(url, httpContentTypeEnum, open, request, response);
        } catch (Exception e) {
            log.error("下载文件失败", e);
            throw new BusinessException("下载文件失败");
        }
    }

    /**
     * @param url <a href="http://localhost:9000/mall/test/20240425/20150919022913sFUmNsFUmN.jpg">...</a>
     */
    @RequestMapping(value = "/download2", method = RequestMethod.POST)
    @ResponseBody
    public BlogResponse<?> download2(@RequestParam("url") String url) {
        redisTemplate.opsForValue().set("url", url);
        return BlogResponse.Success(minioUtils.downloadFile(url));
    }
}
